package ofxdownloader;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
 * The OFX connector is responsible for doing the actual communication
 * with the OFX server
 * @author Alex Spurling
 *
 */
public class OFXConnector {

	@SuppressWarnings("serial")
	public class OFXSignOnException extends Exception {
		public OFXSignOnException(String message) {
			super(message);
		}
	}

	private HttpClient client;

	private static final String NW_URL = "https://pfmanagement.nationet.com/OFXSecurity/OFX_SSL_128.dll";

	public OFXConnector() {

		client = new HttpClient();
	}

	public OFXResponse getOFXResponse(OFXRequest ofxRequest) throws OFXSignOnException {

		System.out.println("*****Sending request*****");
		System.out.println(ofxRequest.toString());

		PostMethod method = new PostMethod(NW_URL);
		RequestEntity request;
		String response = null;
		try {

			request = new StringRequestEntity(ofxRequest.toString(), "application/x-ofx", "UTF-8");
			method.setRequestEntity(request);

			client.executeMethod(method);

			response = method.getResponseBodyAsString();

			System.out.println( "Response: " + response);

		} catch (UnsupportedEncodingException e) {
			//Should never happen
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//clean up the connection resources
		method.releaseConnection();

		//Something must have gone wrong
		if (response == null) return null;
		OFXResponse ofxResponse = new OFXResponse(response);

		//Check for any status errors and throw exceptions if anything is not right
		handleResponseStatus(ofxResponse);

		return ofxResponse;
	}

	/**
	 * Handle a response by throwing an exception when an error is found
	 * @param response
	 * @throws OFXSignOnException
	 */
	private void handleResponseStatus(OFXResponse response) throws OFXSignOnException {
		String statusCode = OFXResponseParser.getStatusCode(response);
		String statusSeverity = OFXResponseParser.getStatusSeverity(response);
		String statusMessage = OFXResponseParser.getStatusMessage(response);

		if (!"0".equals(statusCode)) {
			throw new OFXSignOnException("Sign on error: status code: " + statusCode + " severity: " + statusSeverity + " message: " + statusMessage);
		}
	}

}
